package ru.infosystem.server;

/**
 *
 * @author akoshi
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {  
        
    private ServerSocket server = null;    

    
    public Server( int portNumber ) {            
            
        System.out.println("[INFO] Server start");
        
        boolean  isRunning  = true;
                    
        try {
            
            server = new ServerSocket(portNumber);     
                    
        } catch (IOException e) {           
                    
                    System.out.println("Couldn't listen to port " + portNumber);
                    System.exit(-1);
        }
            
        while(isRunning) {
                    
            try {
                
                Socket socket = server.accept();                                  
                Runnable run = new ThreadedRequestHandler(socket);
                            
                Thread th = new Thread(run);
                th.start();
                
            } catch (IOException e) {
                        
                System.out.println("Can't accept client");                      
                System.exit(1);
            }
        }
            
        System.out.println("[INFO] Server stop");
    }  
   
    public static void main(String args[]) {
        /**         --FOR-DEBUG--   
        Server server = null;
            
        if (args.length != 1)                
                System.out.println("Usage: java SocketServer port");
        else {

            try { 

                    server = new Server(Integer.parseInt(args[0]));                        

            } catch(NumberFormatException nfe) {

                    System.out.println("Port - must be number!");
                    System.exit(1);
            }
        }
        */
        
        Server server = new Server(4444);
    }
}